import React, { useState, useEffect } from 'react';
import { Modal, Transfer, message, Select, Divider, Table, Checkbox } from 'antd';
import { useIntl } from 'umi';
import type { TableListItem } from '../data.d';

export type FormValueType = {} & Partial<TableListItem>;
import { getOrganizeAuth, getRoleAuth } from '../service';

const { Option } = Select;
export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  authModalVisible: boolean;
  values: Partial<TableListItem>;
};

const UpdateAuth: React.FC<UpdateFormProps> = (props) => {

  const findRoleAuth = async (id: string) => {
    const hide = message.loading('正在查询');
    try {
      await getRoleAuth({ id: id }).then(res => {
        let respData = res.data;
        let mockData = [];
        let targetKeys = [];
        //处理下拉组织
        let myOrgData = respData.orgList.map((item: any) => {
          let obj = { name: item.organize_name, value: item.organize_id };
          return obj;
        })
        let object = {};
        myOrgData = myOrgData.reduce((cur: any, next: any) => {
          object[next.value] ? "" : object[next.value] = true && cur.push(next);
          return cur;
        }, []) //设置cur默认类型为数组，并且初始值为空的数组
        setOrgData(myOrgData);
        if (myOrgData.length > 0) {
          let currentOrganize = myOrgData[0].value;
          setCurrentOrganize(currentOrganize);
        }

        //处理角色权限
        for (let i = 0; i < respData.roleLs.length; i++) {
          respData.roleLs[i].key = respData.roleLs[i].id
          respData.roleLs[i].title = respData.roleLs[i].name
          respData.roleLs[i].description = respData.roleLs[i].name
          mockData.push({ key: respData.roleLs[i].id, title: respData.roleLs[i].name, description: respData.roleLs[i].name })
        }
        for (let i = 0; i < respData.myRoleLs.length; i++) {
          mockData.push({ key: respData.myRoleLs[i].id, title: respData.myRoleLs[i].name, description: respData.myRoleLs[i].name })
          targetKeys.push(respData.myRoleLs[i].id)
        }
        setMockData(mockData);
        setTargetKeys(targetKeys);
        findOrganizeAuth(currentOrganize);
      })
      hide();
      // message.success('数据查询成功');
      return true;
    } catch (error) {
      hide();
      // message.error('数据查询失败');
      return false;
    }
  };

  const fommat = (arrayList: any, pidStr = "parent_id", idStr = "id", childrenStr = "children") => {
    let listOjb = {}; // 用来储存{key: obj}格式的对象
    let treeList = []; // 用来储存最终树形结构数据的数组
    // 将数据变换成{key: obj}格式，方便下面处理数据
    for (let i = 0; i < arrayList.length; i++) {
      var data = arrayList[i];
      data.key = data.id;
      data.show_key = data.id + ":" + data.org_cascade;
      data.opera_key = data.id + ":" + data.org_cascade;
      listOjb[arrayList[i][idStr]] = data;
    }
    // 根据pid来将数据进行格式化
    for (let j = 0; j < arrayList.length; j++) {
      // 判断父级是否存在
      let haveParent = listOjb[arrayList[j][pidStr]];
      if (haveParent) {
        // 如果有没有父级children字段，就创建一个children字段
        !haveParent[childrenStr] && (haveParent[childrenStr] = []);
        // 在父级里插入子项
        haveParent[childrenStr].push(arrayList[j]);
      } else {
        // 如果没有父级直接插入到最外层
        treeList.push(arrayList[j]);
      }
    }
    return treeList;
  };

  const remove = (that: any, val: any) => {
    var index = that.indexOf(val);
    if (index > -1) {
      that.splice(index, 1);
    }
  };

  const findOrganizeAuth = async (organize_id:string) => {
    const hide = message.loading('正在查询');
    await getOrganizeAuth({ id: props.values.id, organize_id: organize_id }).then(res => {
      console.log('---查询了组织权限---')
      console.log(res)
      const treeData = fommat(
        res.data.list,
        "pid"
      );
      setOrgAuthData(treeData);
      setShowAuth([]);
      setOperaAuth([])
      const object = res.data.object;
      if (object.showAuthData != "" && object.showAuthData != null) {
        setShowAuth(object.showAuthData.split(","));
      }
      if (object.operaAuthData != "" && object.operaAuthData != null) {
        setOperaAuth(object.operaAuthData.split(","))
      }
      console.log(orgAuthData)
      console.log(showAuth)
      console.log(operaAuth)
    })
    hide();
  }

  useEffect(() => {
    findRoleAuth(props.values.id + "");
  }, [props.authModalVisible]);


  const intl = useIntl();
  let index = 0;
  const handleOk = () => {
    let values = {};
    values = { role_ids: targetKeys.join(","), id: props.values.id, showAuthData: showAuth.join(','), operaAuthData: operaAuth.join(','), organize_id: currentOrganize }
    props.onSubmit(values);
    if (index > 0) {
      props.onCancel()
    }
    index++;
  };
  const handleCancel = () => {
    props.onCancel()
  }

  const [mockData, setMockData] = useState([]);
  const [targetKeys, setTargetKeys] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [orgData, setOrgData] = useState([]);
  const [currentOrganize, setCurrentOrganize] = useState('');
  const [orgAuthData, setOrgAuthData] = useState<any>([]);
  const [showAuth, setShowAuth] = useState([]);
  const [operaAuth, setOperaAuth] = useState([]);



  const onChange = (nextTargetKeys, direction, moveKeys) => {
    // console.log('targetKeys:', nextTargetKeys);
    // console.log('direction:', direction);
    // console.log('moveKeys:', moveKeys);
    setTargetKeys(nextTargetKeys);
  };

  const onSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
    // console.log('sourceSelectedKeys:', sourceSelectedKeys);
    // console.log('targetSelectedKeys:', targetSelectedKeys);
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  const onScroll = (direction, e) => {
    // console.log('direction:', direction);
    // console.log('target:', e.target);
  };
  const selectChange = (e: any) => {
    setCurrentOrganize(e);
    findOrganizeAuth(e);
  };

  const onShowAuthChange = (val: any) => {
    let value = val.target.value;
    if (val.target.checked) {
      showAuth.push(value);
      setShowAuth(showAuth);
    } else {
      remove(showAuth, value);
      setShowAuth(showAuth);
    }
  }

  const onOperaAuthChange = (val: any) => {
    let value = val.target.value;
    if (val.target.checked) {
      operaAuth.push(value);
      setOperaAuth(operaAuth);
    } else {
      remove(operaAuth, value);
      setOperaAuth(operaAuth);
    }
  }

  const columns = [
    {
      title: '名称',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '查看权限',
      key: 'showAuth',
      render: (text: any, record: any) => {
        return <Checkbox value={record.show_key} key={showAuth.indexOf(record.show_key)!=-1} defaultChecked={showAuth.indexOf(record.show_key)!=-1} onChange={onShowAuthChange}></Checkbox>
      },
    },
    {
      title: '操作权限（编辑/删除）',
      key: 'operaAuth',
      render: (text: any, record: any) => {
        return <Checkbox value={record.opera_key} key={operaAuth.indexOf(record.opera_key)!=-1} defaultChecked={operaAuth.indexOf(record.opera_key)!=-1} onChange={onOperaAuthChange}></Checkbox>
      },
    },
  ];

  // setInitValues(props.values);
  return (
    <Modal
      width={800}
      title={intl.formatMessage({
        id: '权限分配',
        defaultMessage: '权限分配',
      })}
      visible={props.authModalVisible}
      destroyOnClose
      onOk={handleOk} onCancel={handleCancel}
    // onFinish={props.onSubmit}
    // onVisibleChange={handleOk}
    // initialValues={props.values}
    >
      <Transfer
        listStyle={{
          width: '600px',
          height: '300px',
          marginLeft: '20px'
        }}
        dataSource={mockData}
        titles={['角色', '授权角色']}
        targetKeys={targetKeys}
        selectedKeys={selectedKeys}
        onChange={onChange}
        onSelectChange={onSelectChange}
        onScroll={onScroll}
        render={item => item.title}
      />
      <Divider />
      <Select
        showSearch
        style={{ width: '100%' }}
        placeholder="请选择"
        // optionFilterProp="children"
        onChange={selectChange}
        value={currentOrganize}
      // onFocus={onFocus}
      // onBlur={onBlur}
      // onSearch={onSearch}
      >
        {
          orgData.map((item: any) => {
            return <Option value={item.value}>{item.name}</Option>
          })
        }

        {/* <Option value="jack">Jack</Option>
        <Option value="lucy">Lucy</Option>
        <Option value="tom">Tom</Option> */}
      </Select>
      <Divider />
      <Table
        columns={columns}
        dataSource={orgAuthData}
        defaultExpandAllRows={true}
        bordered
      />
    </Modal>
  );
};

export default UpdateAuth;
